// import { dataApi } from '@/utils/request'
import { asyncRoutes, constantRoutes } from '@/router'
// eslint-disable-next-line no-unused-vars
// import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission 根据角色验证模块是否显示 不用
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  return true
  // if (route.meta && route.meta.roles) {
  //   return roles.some(role => route.meta.roles.includes(role))
  // } else {
  //   return true
  // }
}

/**
 * Filter asynchronous routing tables by recursion  根据角色验证模块是否显示 不用
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

// 获取模块数据接口
const actions = {
  // 处理路由 不可改用调后台
  async generateRoutes({ commit }, roles) {
    // console.log('处理路由……')
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      // console.log('处理路由……')
      // console.log(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
